package com.liming.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.liming.model.User;
import com.liming.service.UserService;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	UserService userservice=new UserService();
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		if("login".equals(method)){
			Login(req, resp);
		}else if("regist".equals(method)){
			Regist(req,resp);
		}else if("ajaxuser".equals(method)){//判断用户名是否存在
			AjaxUser(req, resp);
		}
	}
	/**
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	private void AjaxUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("ajax判断用户名执行");
		String username=req.getParameter("username");
		if(userservice.isEnable(username.trim()))
			resp.getWriter().write("1");//可用 
		else
			resp.getWriter().write("0");//用户名存在，不可用
	}
	/**
	 * @param req
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void Regist(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException {
		User user=new User();
		user.setUsername(req.getParameter("username"));
		user.setPassword(req.getParameter("password"));
		user.setUserphone(req.getParameter("userphone"));
		user.setUseremail(req.getParameter("useremail"));
		if(userservice.regist(user)) {
				resp.sendRedirect(req.getContextPath()+"/login.jsp");
		}else {
			req.setAttribute("message", "注册失败！");
			req.getRequestDispatcher("login.jsp").forward(req, resp);
		}
	}
	/**
	 * @param req
	 * @param resp
	 * @throws IOException
	 * @throws ServletException
	 */
	private void Login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		System.out.println("login执行");
		String username=req.getParameter("username");
		String password=req.getParameter("password");
		HttpSession session=req.getSession();
		User user = userservice.login(username, password);
		session.setAttribute("message", null);
		session.setAttribute("user",user );
		if(user!=null)
		{	
			resp.sendRedirect(req.getContextPath()+"/index.jsp");
		}else{
			req.setAttribute("message", "用户名或密码错误！");
			req.getRequestDispatcher("login.jsp").forward(req, resp);
		}
	}

}
